﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Threading;
using System.Drawing;

namespace fetco.service
{
    public class Utility
    {
        public Utility()
        {

        }

        // Regular Expression
        public static string ValidationExpressionEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
        public static string ValidationExpressionTel = @"^[0-9]+$";
        public static string ValidationExpressionLatin = @"^[0-9a-zA-Z. _-]+$";
        public static string ValidationExpressionNumberWithComma = @"^[0-9,.]+$";
        public static string ValidationExpressionIntWithComma = @"^[0-9,]+$";
        public static string ValidationExpressionIntWithCommaMinus = @"^[-]*[0-9,]+$";
        public static string ValidationExpressionIntWithNoComma = @"^[0-9]+$";
        public static string ValidationExressionFloatWithDot = @"^[0-9,.]+$";
        public static string StrFormatDate = "dd/mm/yyyy";

        public static Hashtable Dictionary = new Hashtable();
        public static Hashtable XMLObject = new Hashtable();

        public static string Encrypt(string mess)
        {
            MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(mess);
            bs = x.ComputeHash(bs);
            StringBuilder s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString().ToUpper();
        }

        public static long ParseToBigint(string number)
        {
            long result;
            if (!string.IsNullOrEmpty(number))
            {
                string strnumber = number.Replace(",", string.Empty);
                result = long.Parse(strnumber);
            }
            else
            {
                result = 0;
            }
            return result;
        }

        public static double ParsePercentToDouble(string percent)
        {
            double result;
            string[] valuelist = percent.Split('%');
            if (valuelist.Length != 2)
                return 0;
            result = double.Parse(valuelist[0]) / 100;
            return result;
        }

        public static DateTime ParseDateTime(string value)
        {
            string year;
            string month;
            string day;

            string[] valueList = value.Split('-');
            if (valueList.Length != 3)
                return new DateTime(1900, 1, 1, 0, 0, 0, 0);
            year = valueList[2];
            month = valueList[1];
            day = valueList[0];

            value = year + "/" + month + "/" + day;

            string hour = string.Empty;
            string minute = string.Empty;
            DateTime result;

            try { result = DateTime.Parse(value); }
            catch { result = DateTime.MinValue; }
            return result;
        }

        public static string SplitString(string source, int length)
        {
            if (source.Length < length)
                return source;
            else
            {
                int i = length - 1;
                while (source[i] != ' ' && i < source.Length)
                {
                    i--;
                }
                return source.Substring(0, i + 1);
            }
        }

        public static string Splitword(string Textstring)
        {
            string strtext = "";
            string returntext = "";
            String[] temp;
            char[] separator = { '$', '#', '@', '!', '%', '^', '&', '*', '(', ')', '=', '|', '_', '-', ',', '"' }; //ki tu can cắt
            temp = Textstring.Split(separator);
            foreach (string textreturn in temp)
            {
                strtext += textreturn;
                returntext = strtext.ToLower();
            }
            return returntext;
        }

        public static string SplitwordEnd(string Textstring)
        {
            string strtext = "";
            String[] temp;
            char[] separator = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',' }; //ki tu can cắt
            temp = Textstring.Split(separator);
            foreach (string textreturn in temp)
            {
                strtext += textreturn;
            }

            return strtext;
        }

        public static string StripHtml(string html, bool allowHarmlessTags)
        {
            if (html == null || html == string.Empty)
                return string.Empty;

            if (allowHarmlessTags)
                return Regex.Replace(html, "", string.Empty);

            return Regex.Replace(html, "<[^>]*>", string.Empty);
        }

        public static string StripDiacritics(string accented)
        {
            Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(NormalizationForm.FormD);
            string s = regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(' ', '-').Replace(':', '-')
                .Replace('?', '-').Replace('_', '-').Replace('%', '-').Replace('.', '-').Replace('/', '-').Replace('&', '-').Replace('!', '-')
                .Replace('@', '-').Replace('#', '-').Replace('$', '-').Replace('^', '-').Replace('*', '-').Replace('+', '-').Replace(',', '-');
            while (s.Contains("--"))
                s = s.Replace("--", "-");
            return s;
        }

        public static string ShortSummary(int length, string temp)
        {
            string result;
            result = temp;
            if (temp.Length > length)
            {
                string t = temp.Substring(0, length - 1);
                if (t.LastIndexOf(' ') != -1)
                {
                    result = t.Substring(0, t.LastIndexOf(' ')) + " ...";
                }
            }
            return result;
        }

        public static bool SendMail(string subject, string content, string mailFrom, string mailTo)
        {
            bool flag = true;
            try
            {
                SmtpClient SmtpMail = new SmtpClient();
                MailMessage MessageMail = new MailMessage(mailFrom, mailTo);
                MessageMail.Subject = subject;
                MessageMail.IsBodyHtml = true;
                MessageMail.BodyEncoding = System.Text.Encoding.UTF8;
                MessageMail.Body = content;
                SmtpMail.Send(MessageMail);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool GetYahooStatus(string yahooId)
        {
            try
            {
                WebClient wcImage = new WebClient();
                string URL = "http://opi.yahoo.com/online?u=" + yahooId + "&m=a&t=1";
                string t = wcImage.DownloadString(URL);
                if (t == "00")
                    return false;
                return true;
            }
            catch { return false; }
        }

        public static void DelImage(string file, string path)
        {
            try
            {
                if (File.Exists(Path.Combine(path, file)))
                    File.Delete(Path.Combine(path, file));
            }
            catch
            {
                throw new Exception();
            }
        }

        public static string UploadFile(FileUpload Upload, string path)
        {
            HttpPostedFile postedFile = Upload.PostedFile;
            string fileName = string.Empty;
            if (postedFile != null && postedFile.InputStream != null && postedFile.ContentLength > 0)
            {
                Thread.Sleep(1000);
                Random random = new Random();
                long tmp = DateTime.Now.Ticks + random.Next(100);
                fileName = tmp.ToString() + Path.GetExtension(postedFile.FileName);
                postedFile.SaveAs(Path.Combine(path, fileName));
            }
            return fileName;
        }

        /*public static string UploadFileImage(HttpPostedFile postedFile, string path, int Width, int Height, int Maxsize, bool IsResize)
        {
            try
            {
                //HttpPostedFile postedFile = Upload.PostedFile;
                if (postedFile != null && postedFile.InputStream != null && postedFile.ContentLength > 0)
                {
                    if (!Regex.IsMatch(postedFile.ContentType, "image/\\S+"))
                    {
                        return string.Empty;
                    }
                    if (postedFile.ContentLength > Maxsize * 1000)
                        return string.Empty;
                    Thread.Sleep(1000);
                    Random random = new Random();
                    long tmp = DateTime.Now.Ticks + random.Next(100);
                    string fileName = tmp.ToString() + Path.GetExtension(postedFile.FileName);
                    if (!IsResize)
                    {
                        postedFile.SaveAs(Path.Combine(path, fileName));
                        return fileName;
                    }
                    else
                    {
                        postedFile.SaveAs(Path.Combine(path, fileName));
                        Bitmap detail = new Bitmap(Path.Combine(path, fileName));
                        string fileName1 = DateTime.Now.Ticks.ToString() + Path.GetExtension(postedFile.FileName);
                        ImageUtility.ResizePhotoNoBackground((System.Drawing.Image)detail, Width,
                            Height, path, fileName1);
                        detail.Dispose();
                        File.Delete(Path.Combine(path, fileName));
                        return fileName1;
                    }
                }
            }
            catch
            {
                return string.Empty;
            }
            return string.Empty;
        }*/

        public static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

        public static string GenerateRandomCode(int amount)
        {
            Random random = new Random();
            string s = "";
            char[] alpha ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G',
                'H','I','J','K','L','M','N','O','P','Q','S','R','T','U','X','Y','V','W','Z'};
            for (int i = 0; i < amount; i++)
            {
                int tmp = random.Next(36);
                s = String.Concat(s, alpha[tmp].ToString());
            }
            return s;
        }

        public static void SetDropdownListIndex(DropDownList ddl, long indexvalue)
        {
            if (indexvalue != long.MinValue && indexvalue > 0)
            {
                ListItem item = ddl.Items.FindByValue(indexvalue.ToString());
                if (item != null)
                    ddl.SelectedIndex = ddl.Items.IndexOf(item);
            }
            else
                ddl.SelectedIndex = 0;
        }

        public static int GetSession(object session)
        {
            try
            {
                if (session == null)
                    return 1;
                return (int)session;
            }
            catch (Exception)
            {
                return 0;
            }

        }

        const string FindText = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ";
        const string ReplText = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";
        public static string ChuyenTVKhongDau(string strVietNamese)
        {
            int index = -1;
            while ((index = strVietNamese.IndexOfAny(FindText.ToCharArray())) != -1)
            {
                int index2 = FindText.IndexOf(strVietNamese[index]);
                strVietNamese = strVietNamese.Replace(strVietNamese[index], ReplText[index2]);
            }
            return strVietNamese;
        }
        public static string EscapeString(string textstring)
        {
            string newstring = textstring.Replace("'", "''");
            return newstring;
        }

    }

}
